package com.mb.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.mb.mp.service.IFileUploadService;
import com.mb.common.controller.BaseController;
import com.mb.common.utils.Base64Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 文件上传 controller
 * @author mihcael.li
 * @create 2018-03-24 下午4:17
 **/
@Controller
@RequestMapping("/api")
public class FileUploadController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private IFileUploadService fileUploadService;

    /**
     * 上传文件
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/fileUpload")
    public String fileUpload(HttpServletRequest request) {
        String resp = "";
        String base64Str = request.getParameter("base64Str");
        String fileType = request.getParameter("fileType");

        JSONObject reqData = new JSONObject();
        reqData.put("base64Str",base64Str);
        reqData.put("fileType",fileType);

        JSONObject respData = fileUploadService.fileUpload(reqData);
        resp = respData.toJSONString();
        resp = Base64Utils.encode(resp);
        return resp;
    }


    /**
     * 上传文件multipart
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/fileUploadByMult")
    public String fileUploadByMult(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String resp = "";
        JSONObject reqData = new JSONObject();
        JSONObject respData = fileUploadService.fileUploadByMult(file,reqData);
        resp = respData.toJSONString();
        resp = Base64Utils.encode(resp);
        return resp;
    }

}
